package com.xiaotu.spider.sohu.pageprocessor;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.xiaotu.common.model.TVPubCommentModel;
import com.xiaotu.common.util.HttpJsonReaderUtils;
import com.xiaotu.common.util.StringUtil;
import com.xiaotu.common.util.Constants;

/**
 * 获取搜狐视频 TV jsonp数据
 * 
 * tab_tv_comment
 */
public class SohuHttpProcessor {

	private final Logger log = LoggerFactory.getLogger(SohuHttpProcessor.class);

	// 剧名
	private JSONObject tvInfo;

	// URL Parameter
	private String topic_url = "";

	private String topic_title = "";

	private String topic_source_id = "";

	private String topic_category_id = "";

	private String vid = "";

	private String cid = "";

	private String playlistId = "";
	

	@SuppressWarnings("unused")
	private SohuHttpProcessor() {
	};

	/**
	 * 创建对象必须传入以下搜狐页面信息 剧名,剧二级子页面url,剧playlistId,剧vid,剧分类
	 * 
	 * @param 剧名
	 *            resourceName，如【花千骨】
	 * @param 剧二级子页面
	 *            tvItemUrl，如【http://tv.sohu.com/item/MTE5NDMzMQ==.html】
	 * @param 剧
	 *            playlistId,如【7050666】
	 * @param 剧
	 *            vid,如【2412969】
	 * @param 剧分类
	 *            cid,如【2】
	 */
	public SohuHttpProcessor(JSONObject tvInfo, String tvItemUrl,
			String playlistId, String vid, String cid) {
		
		this.tvInfo = tvInfo;
		
		this.topic_title = tvInfo.getString("tvName").replace("·", "");
		
		this.topic_url = tvItemUrl;
		
		this.topic_source_id=playlistId;
		
		this.playlistId=playlistId;
		
		this.cid=cid;
		
		this.topic_category_id=cid;
		
		this.vid=vid;
	}

	// url info
	private String searchURL = " http://changyan.sohu.com/api/services/topic/load?callback=fn";

	private String searchPrm1 = "&flag=true"
			+ "&src=http://changyan.sohu.com/api/services/topic/load"
			+ "&client_id=cyqyBluaj" + "&outer_page_size=10"
			+ "&outer_page_no=1" + "&topic_url=";

	private String searchPrm2 = "&topic_title=";

	private String searchPrm3 = "&topic_source_id=";

	private String searchPrm4 = "&topic_parent_id=" + "&topic_owner_id="
			+ "&style=terrace" + "&refresh=true" + "&order_by=time"
			+ "&topic_category_id=";

	private String searchPrm5 = "&topic_metadata={\"vid\":\"";

	private String searchPrm6 = "\",\"cid\":\"";

	private String searchPrm7 = "\",\"playlistId\":\"";

	private String searchPrm8 = "\",\"subcid\":\"\"}";
	List<TVPubCommentModel> modelList = new ArrayList<TVPubCommentModel>();
	
	public List<TVPubCommentModel> process() {
		
		try {
				// comb url
				String params = searchPrm1 + topic_url + searchPrm2
						+ topic_title + searchPrm3 + topic_source_id
						+ searchPrm4 + topic_category_id + searchPrm5 + vid
						+ searchPrm6 + cid + searchPrm7 + playlistId
						+ searchPrm8;
				 
				System.out.println(searchURL);
				System.out.println(params);

				// get json from http url
				String JsonStr = HttpJsonReaderUtils.GetFromHtml(searchURL + params, null);

				if (JsonStr.equals("") || JsonStr == null) {
					//System.out.println(resourceName + "--失败");
					return null;
				}

				//System.out.println(JsonStr);
				modelList=getCommentModel(JsonStr);

				return modelList;

		} catch (Exception e) {

			e.printStackTrace();
			// log
//			SpiderUtil.taskLog(e,Constants.SiteName.SOHU);
//			log.error(cid, e.printStackTrace());
		}
		// log
//		SpiderUtil.taskLog(modelList,Constants.SiteName.SOHU);
		return modelList;
	}
	
	public List<TVPubCommentModel> process2(){
		
		try {
			searchURL ="http://changyan.sohu.com/api/2/topic/load?client_id=cyqyBluaj&topic_url="+topic_url+"&topic_source_id=vp"+playlistId+"&page_size=30";
			
			String JsonStr = HttpJsonReaderUtils.GetFromHtml(searchURL, null);

			if (JsonStr.equals("") || JsonStr == null) {
				
				return null;
			}

			//System.out.println(JsonStr);
			modelList=getCommentModel(JsonStr);

			return modelList;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return modelList;
	}

	// get comment list from json
	private List<TVPubCommentModel> getCommentModel(String jsonStr) {

		List<TVPubCommentModel> modelList = new ArrayList<TVPubCommentModel>();

		try {
			// format json
			jsonStr = jsonStr.substring(jsonStr.indexOf("{"));

			jsonStr = jsonStr.substring(0, jsonStr.lastIndexOf("}") + 1);

			// System.out.println(personStr);

			JSONObject C_json = JSONObject.fromObject(jsonStr);

			// for each comments
			if (C_json.containsKey("comments")) {

				JSONArray comments = C_json.getJSONArray("comments");

				for (int i = 0; i < comments.size(); i++) {

					// comment model
					TVPubCommentModel model = new TVPubCommentModel();
					model.setTvName(tvInfo.getString("tvName"));
					model.setTvId(tvInfo.getString("tvid"));
					model.setResourceSiteId(Constants.SiteName.SOHU);

					// get comment model attribution value
					JSONObject comment = comments.getJSONObject(i);

					if (comment.containsKey("content")) {
						model.setContent(comment.getString("content").replace(
								"'", "''"));
					}

					if (comment.containsKey("create_time")) {
						String time = comment.getString("create_time");
						if(StringUtil.isEmpty(time)){
							continue;
						}
//						model.setCommentDate(new Date(Long.valueOf(time)));
						model.setCommentDate(time);
					}

					if (comment.containsKey("passport")) {
						JSONObject user = comment.getJSONObject("passport");
						model.setCommentUser(user.getString("nickname")
								.replace("'", "''"));
					}

					if (StringUtil.isNotEmpty(model.getContent())) {
						modelList.add(model);
					}
				}
			}
		} catch (Exception e) {
			log.error("搜狐TV评论 json 内容读取出错，" + e.getMessage());
		}

		return modelList;
	}

	/**
	 * 把毫秒转化成日期
	 * 
	 * @param dateFormat
	 *            (日期格式，例如：MM/ dd/yyyy HH:mm:ss)
	 * @param millSec
	 *            (毫秒数)
	 * @return
	 */
	@SuppressWarnings("unused")
	private String transferLongToDate(String dateFormat, Long millSec) {
		SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
		Date date = new Date(millSec);
		return sdf.format(date);
	}

	public static void main(String[] args) {
//		HttpProcessor process = new SohuHttpProcessor(
//				"花千骨",
//				"http://tv.sohu.com/item/MTE5NDMzMQ==.html",
//				"7050666",
//				"2412969",
//				"2");
//		process.process();
	}

}
